package cp7_jstl_javabean.user;

import util.DBTool;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/cp7/user/save")
public class SaveUserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置读取数据的编码
        req.setCharacterEncoding("utf-8");
        // 获取到表单提交的参数
        String nickname = req.getParameter("nickname");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        // 拼接insert语句
        String sql = "insert into userinfo (nickname,account,password,email) " +
                "values ('" + nickname + "','" + account + "','" + password + "','" + email + "')";
        System.out.println(sql);
        PrintWriter out = StringUtil.getWriter(resp);// 获取输出对象
        try {
            // 执行插入语句获取受影响函数
            int count = DBTool.executeUpdate(sql);
            if(count == 0){
                out.println("插入数据失败");
            }else{
                // 保存成功 跳转到列表也
                resp.sendRedirect("/cp7/user/list");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
